package com.ctrip.cap.internal.appium.suite.android;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctrip.cap.appium.WaitUtils;
import com.ctrip.cap.device.Device;
import com.ctrip.cap.device.android.impl.DefaultDeviceStore;

/**
 * Selendroid 安装包冲突，临时采用等待错开。
 * 
 * @author ltyao
 *
 */
public class SelendroidBuddy {

	private static final SelendroidBuddy buddy = new SelendroidBuddy(
			DefaultDeviceStore.getInstance().getDevices());;

	private final Map<Device, AtomicBoolean> deviceWaited = new HashMap<>();

	private static final Logger logger = LoggerFactory
			.getLogger(SelendroidBuddy.class);

	private static final long sleepInSeconds = 20;

	private int index = 0;

	public SelendroidBuddy(Set<? extends Device> set) {
		for (Device device : set) {
			deviceWaited.put(device, new AtomicBoolean());
		}
	}

	public synchronized void sleep() {
		if (++index > deviceWaited.size()) {
			return;
		}
		for (Map.Entry<Device, AtomicBoolean> entry : deviceWaited.entrySet()) {
			if (!entry.getValue().get()) {
				entry.getValue().set(true);
				logger.info("sleep {} seconds for selendroid", sleepInSeconds
						* (index - 1));
				WaitUtils.sleepTightInSeconds(sleepInSeconds * (index - 1));
				break;
			}
		}
	}

	public static void sleeping() {
		buddy.sleep();
	}
}
